package com.hjj.concurrence.artOfConcurrent.t1;

/**
 * 演示串行和并发执行并累加操作的时间
 *
 * @author hjj
 * @create 2019-12-16 13:55
 */
public class ConcurrencyTest {
    /**
     * concurrency: 1ms, b=-10001
     * serial:0ms,b=-10001,a=50005
     */
//    private static final long count = 10001;
    /**
     * concurrency: 4ms, b=-100001
     * serial:4ms,b=-100001,a=500005
     */
//    private static final long count = 100001;
    /**
     * concurrency: 10ms, b=-1000001
     * serial:9ms,b=-1000001,a=5000005
     */
//    private static final long count = 1000001;
    /**
     * concurrency: 13ms, b=-10000001
     * serial:18ms,b=-10000001,a=50000005
     */
//    private static final long count = 10000001;

    /**
     * concurrency: 83ms, b=-100000001
     * serial:135ms,b=-100000001,a=500000005
     */
//    private static final long count = 100000001;

    /**
     * concurrency: 776ms, b=-1000000001
     * serial:1405ms,b=-1000000001,a=705032709
     */
    private static final long count = 1000000001;


    private static void concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 5;
                }
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        thread.join();
        System.out.println("concurrency: " + time + "ms, b=" + b);
    }

    private static void serial() {
        long start = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i < count; i++) {
            a += 5;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("serial:" + time + "ms,b=" + b + ",a=" + a);
    }

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();
    }
}
